using System;
using System.Globalization;
using System.Web.UI.WebControls;
using mojoPortal.Web;
using mojoPortal.Web.Framework;
using mojoPortal.Web.UI;
using Resources;
using eStore.Business;
using eStore.Helpers;
using System.Collections;
using mojoPortal.Business;
using ud_Utilities;
using mojoPortal.Business.WebHelpers;

namespace eStore.UI
{
    public partial class AdminProductPage : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        private string pageNumberParam;
        //private string sortParam;
        //private string sort = "Name";
        private Store store;
        private eStoreConfiguration config = new eStoreConfiguration();
        readonly eStoreDB repository = new eStoreDB();
        private SiteUser siteUser;
        protected string DeleteLinkImage = WebConfigSettings.DeleteLinkImage;
        protected string EditContentImage = WebConfigSettings.EditContentImage;

        protected void Page_Load(object sender, EventArgs e)
        {
            LoadSettings();

            if (!UserCanEditModule(moduleId))
            {
                SiteUtils.RedirectToAccessDeniedPage();
                return;
            }

            SetupCss();
            PopulateLabels();
            PopulateControls();

        }

        private void PopulateControls()
        {
            if (store == null) { return; }

            if (!Page.IsPostBack)
            {
                BindGrid();
            }

        }



        private void BindGrid()
        {
            if (store == null) { return; }
            int totalRecords;
            grdProduct.DataSource = repository.GeteStoreProductByModuleID(store.Guid, out totalRecords);

            grdProduct.AllowPaging = totalRecords > 10;
            grdProduct.DataBind();
            
        }

        //private void grdProduct_Sorting(object sender, GridViewSortEventArgs e)
        //{

        //    String redirectUrl = WebUtils.GetSiteRoot()
        //        + "/eStore/AdminProduct.aspx?pageid=" + pageId.ToString(CultureInfo.InvariantCulture)
        //        + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture)
        //        + "&pagenumber"
        //        + moduleId.ToString(CultureInfo.InvariantCulture)
        //        + "=" + pageNumber.ToString(CultureInfo.InvariantCulture)
        //        + "&sort"
        //        + moduleId.ToString(CultureInfo.InvariantCulture)
        //        + "=" + e.SortExpression;

        //    WebUtils.SetupRedirect(this, redirectUrl);

        //}

        //private void btnAddNew_Click(object sender, EventArgs e)
        //{
        //    String redirectUrl = SiteRoot
        //        + "/eStore/AdminProductEdit.aspx?pageid=" + pageId.ToString(CultureInfo.InvariantCulture)
        //        + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);

        //    WebUtils.SetupRedirect(this, redirectUrl);
        //}

        protected string BuildProductQueryString(string productID)
        {

            string result = "?pageid=" + pageId.ToString(CultureInfo.InvariantCulture)
                + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture)
                + "&product=" + productID;

            return result;

        }

        void grdProduct_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton ibtnDelete = e.Row.FindControl("ibtnDelete") as ImageButton;
                Utilities.AddConfirmButton(ibtnDelete, eStoreResources.ConfirmDelete);
            }
        }

        void grdProduct_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("DeleteItem"))
            {
                Guid productGuid = new Guid(e.CommandArgument.ToString());
                if (productGuid != Guid.Empty)
                {
                    if (config.IndexProductsInSearch)
                    {
                        Product product = new Product(productGuid);
                        ContentChangedEventArgs args = new ContentChangedEventArgs {IsDeleted = true};
                        product_ContentChanged(product, args);
                    }

                    FriendlyUrl.DeleteByPageGuid(productGuid);

                    Product.Delete(productGuid);

                    SiteUtils.QueueIndexing();
                    BindGrid();
                }
            }
        }

        void product_ContentChanged(object sender, ContentChangedEventArgs e)
        {
            IndexBuilderProvider indexBuilder = IndexBuilderManager.Providers["eStoreProductIndexBuilderProvider"];
            if (indexBuilder != null)
            {
                indexBuilder.ContentChangedHandler(sender, e);
            }
        }

        private void PopulateLabels()
        {
            lnkStoreMenu.Text = eStoreResources.StoreManagerHeading;
            lnkStoreMenu.NavigateUrl = SiteRoot + "/eStore/AdminDashboard.aspx?pageid="
                                       + pageId.ToString(CultureInfo.InvariantCulture)
                                       + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);

            lnkCurrentPage.Text = eStoreResources.ProductAdministrationLink;
            lnkCurrentPage.NavigateUrl = Request.Url.ToString();

            Title = SiteUtils.FormatPageTitle(siteSettings, eStoreResources.ProductAdministrationLink);
            ltrTitle.Text = eStoreResources.ProductAdministrationLink;
            grdProduct.Columns[0].HeaderText = eStoreResources.ProductNameLabel;
            grdProduct.Columns[1].HeaderText = eStoreResources.ProductIsVisibleLabel;
            grdProduct.Columns[2].HeaderText = eStoreResources.ProductIsSpecialLabel;
            grdProduct.Columns[3].HeaderText = eStoreResources.CategoryName;


            btnAddNew.Text = eStoreResources.ProductAddNewButton;
            btnAddNew.PostBackUrl = SiteRoot
                + "/eStore/AdminProductEdit.aspx?pageid=" + pageId.ToString(CultureInfo.InvariantCulture)
                + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);

        }

        private void LoadSettings()
        {
            if (CurrentPage.ContainsModule(moduleId))
            {
                //store = StoreHelper.GetStore(siteSettings.SiteGuid, moduleId);
                store = StoreHelper.GetStore();
            }

            pageNumberParam = "pagenumber" + moduleId.ToString(CultureInfo.InvariantCulture);
            WebUtils.ParseInt32FromQueryString(pageNumberParam, 1);

            //sortParam = "sort" + moduleId.ToString(CultureInfo.InvariantCulture);

            //if (Page.Request.Params[sortParam] != null)
            //{
            //    sort = Page.Request.Params[sortParam];
            //}
            if (siteUser == null) siteUser = SiteUtils.GetCurrentSiteUser();

        }

        protected virtual void SetupCss()
        {
            // older skins have this
            if (Page.Master == null) return;
            StyleSheet stylesheet = (StyleSheet)Page.Master.FindControl("StyleSheet");
            if (stylesheet == null) return;
            if (stylesheet.FindControl("styleestore") != null) return;
            Literal cssLink = new Literal
            {
                ID = "styleestore",
                Text = @"<link href='"
                       + SiteUtils.GetSkinBaseUrl()
                       + @"styleestore.css' type='text/css' rel='stylesheet' media='screen' />"
            };

            stylesheet.Controls.Add(cssLink);
        }

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);
        }

        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            config = new eStoreConfiguration(settings);
            LoadSideContent(false, false, true, true, 0);
        }
        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
        }

        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);
            Load += Page_Load;
            grdProduct.RowCommand += grdProduct_RowCommand;
            grdProduct.RowDataBound += grdProduct_RowDataBound;
            grdProduct.PageIndexChanging += grdProduct_PageIndexChanging;
            //grdProduct.Sorting += new GridViewSortEventHandler(grdProduct_Sorting);
            //btnAddNew.Click += new EventHandler(btnAddNew_Click);
            SuppressPageMenu();
        }

        void grdProduct_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdProduct.PageIndex = e.NewPageIndex;
            BindGrid();
        }
        #endregion
    }
}
